package com.leyou.auth.controller;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.pojo.UserInfo;
import com.leyou.auth.service.AuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@EnableConfigurationProperties(JwtProperties.class)
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private JwtProperties prop;

    @PostMapping("accredit")
    public ResponseEntity<Void> authentication(
            HttpServletRequest request, HttpServletResponse response,
            @RequestParam("username") String username, @RequestParam("password") String password) {
        String token = authService.authentication(username, password);
        if (StringUtils.isBlank(token)) {
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        }
        // 将token写入cookie,并指定httpOnly为true，防止通过JS获取和修改
        CookieUtils.setCookie(request, response, prop.getCookieName(), token, prop.getCookieMaxAge(), null, true);

        return new ResponseEntity<>(HttpStatus.OK);
    }

    @GetMapping("verify")
    public ResponseEntity<UserInfo> verifyUser(
            HttpServletRequest request, HttpServletResponse response, @CookieValue(value = "LY_TOKEN", defaultValue = "") String token) {
        try {
            // 获取token信息
            UserInfo user = JwtUtils.getInfoFromToken(token, prop.getPublicKey());

            // 如果成功，我们还需要刷新token
            String newToken = JwtUtils.generateToken(user, prop.getPrivateKey(), prop.getExpire());

            // 将token写入cookie,并指定httpOnly为true，防止通过JS获取和修改
            CookieUtils.setCookie(request, response, prop.getCookieName(), newToken, prop.getCookieMaxAge());

            return ResponseEntity.ok(user);
        } catch (Exception e) {
            // 抛出异常，证明token无效，直接返回401
            return new ResponseEntity(HttpStatus.UNAUTHORIZED);
        }
    }

    @GetMapping("logout")
    public void logoutUser(
            HttpServletRequest request, HttpServletResponse response) {
        //删除cookie
        CookieUtils.setCookie(request, response, prop.getCookieName(), "", prop.getCookieMaxAge());
    }
}
